package com.ruoyi.controller.quality;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.domain.quality.MesQualityInspection;
import com.ruoyi.service.quality.IMesQualityInspectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 质量检验记录Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/quality/inspection")
public class MesQualityInspectionController extends BaseController
{
    @Autowired
    private IMesQualityInspectionService IMesQualityInspectionService;

    /**
     * 查询质量检验记录列表
     */
    @PreAuthorize("@ss.hasPermi('quality:inspection:list')")
    @GetMapping("/list")
    public TableDataInfo list(MesQualityInspection mesQualityInspection)
    {
        startPage();
        List<MesQualityInspection> list = IMesQualityInspectionService.selectMesQualityInspectionList(mesQualityInspection);
        return getDataTable(list);
    }

    /**
     * 导出质量检验记录列表
     */
    @PreAuthorize("@ss.hasPermi('quality:inspection:export')")
    @Log(title = "质量检验记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MesQualityInspection mesQualityInspection)
    {
        List<MesQualityInspection> list = IMesQualityInspectionService.selectMesQualityInspectionList(mesQualityInspection);
        ExcelUtil<MesQualityInspection> util = new ExcelUtil<MesQualityInspection>(MesQualityInspection.class);
        util.exportExcel(response, list, "质量检验记录数据");
    }

    /**
     * 获取质量检验记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('quality:inspection:query')")
    @GetMapping(value = "/{inspectionId}")
    public AjaxResult getInfo(@PathVariable("inspectionId") Long inspectionId)
    {
        return success(IMesQualityInspectionService.selectMesQualityInspectionByInspectionId(inspectionId));
    }

    /**
     * 新增质量检验记录
     */
    @PreAuthorize("@ss.hasPermi('quality:inspection:add')")
    @Log(title = "质量检验记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MesQualityInspection mesQualityInspection)
    {
        if ("1".equals(IMesQualityInspectionService.checkInspectionCodeUnique(mesQualityInspection.getStandardCode(),mesQualityInspection.getStandardId())))
        {
            return error("新增检验标准'" + mesQualityInspection.getStandardCode() + "'失败，检验标准编码已存在");
        }
        return toAjax(IMesQualityInspectionService.insertMesQualityInspection(mesQualityInspection));
    }

    /**
     * 修改质量检验记录
     */
    @PreAuthorize("@ss.hasPermi('quality:inspection:edit')")
    @Log(title = "质量检验记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MesQualityInspection mesQualityInspection)
    {
        if ("1".equals(IMesQualityInspectionService.checkInspectionCodeUnique(mesQualityInspection.getStandardCode(),mesQualityInspection.getStandardId())))
        {
            return error("修改检验标准'" + mesQualityInspection.getStandardCode() + "'失败，检验标准编码已存在");
        }
        return toAjax(IMesQualityInspectionService.updateMesQualityInspection(mesQualityInspection));
    }

    /**
     * 删除质量检验记录
     */
    @PreAuthorize("@ss.hasPermi('quality:inspection:remove')")
    @Log(title = "质量检验记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{inspectionIds}")
    public AjaxResult remove(@PathVariable Long[] inspectionIds)
    {
        return toAjax(IMesQualityInspectionService.deleteMesQualityInspectionByInspectionIds(inspectionIds));
    }

    /**
     * 校验检验单号是否唯一
     */
    @GetMapping("/checkInspectionCodeUnique")
    public AjaxResult checkInspectionCodeUnique(String inspectionCode , Long inspectionId)
    {
        String result = IMesQualityInspectionService.checkInspectionCodeUnique(inspectionCode,inspectionId);
        return AjaxResult.success(result.equals("0")); // 返回true表示编码已存在，false表示编码可用
    }

    /**
     * 根据工单ID查询检验记录列表
     */
    @GetMapping("/workOrder/{workOrderId}")
    public AjaxResult getInspectionsByWorkOrderId(@PathVariable Long workOrderId)
    {
        List<MesQualityInspection> list = IMesQualityInspectionService.selectInspectionsByWorkOrderId(workOrderId);
        return success(list);
    }

    /**
     * 根据工单编号查询检验记录列表
     */
    @GetMapping("/workOrderCode/{workOrderCode}")
    public AjaxResult getInspectionsByWorkOrderCode(@PathVariable String workOrderCode)
    {
        List<MesQualityInspection> list = IMesQualityInspectionService.selectInspectionsByWorkOrderCode(workOrderCode);
        return success(list);
    }

    /**
     * 根据检验类型查询检验记录列表
     */
    @GetMapping("/type/{type}")
    public AjaxResult getInspectionsByType(@PathVariable String type)
    {
        List<MesQualityInspection> list = IMesQualityInspectionService.selectInspectionsByType(type);
        return success(list);
    }

    /**
     * 根据检验员查询检验记录列表
     */
    @GetMapping("/inspector/{inspector}")
    public AjaxResult getInspectionsByInspector(@PathVariable String inspector)
    {
        List<MesQualityInspection> list = IMesQualityInspectionService.selectInspectionsByInspector(inspector);
        return success(list);
    }

    /**
     * 根据状态查询检验记录列表
     */
    @GetMapping("/status/{status}")
    public AjaxResult getInspectionsByStatus(@PathVariable String status)
    {
        List<MesQualityInspection> list = IMesQualityInspectionService.selectInspectionsByStatus(status);
        return success(list);
    }

    /**
     * 创建采购入库质检记录
     */
    @PreAuthorize("@ss.hasPermi('quality:inspection:add')")
    @Log(title = "创建采购入库质检", businessType = BusinessType.INSERT)
    @PostMapping("/createIQC")
    public AjaxResult createIQCInspection(@RequestBody Map<String, Object> params) {
        Long receiptId = Long.valueOf(params.get("receiptId").toString());
        Long standardId = Long.valueOf(params.get("standardId").toString());
        
        MesQualityInspection inspection = IMesQualityInspectionService.createIQCInspection(receiptId, standardId);
        return AjaxResult.success(inspection);
    }

    /**
     * 处理采购入库质检结果
     */
    @PreAuthorize("@ss.hasPermi('quality:inspection:edit')")
    @Log(title = "处理采购入库质检结果", businessType = BusinessType.UPDATE)
    @PutMapping("/processIQC")
    public AjaxResult processIQCResult(@RequestBody Map<String, Object> params) {
        Long inspectionId = Long.valueOf(params.get("inspectionId").toString());
        String conclusion = params.get("conclusion").toString();
        String remark = params.get("remark") != null ? params.get("remark").toString() : null;
        
        return toAjax(IMesQualityInspectionService.processIQCResult(inspectionId, conclusion, remark));
    }

    /**
     * 创建制造过程质检记录
     */
    @PreAuthorize("@ss.hasPermi('quality:inspection:add')")
    @Log(title = "创建制造过程质检", businessType = BusinessType.INSERT)
    @PostMapping("/createIPQC")
    public AjaxResult createIPQCInspection(@RequestBody Map<String, Object> params) {
        Long workOrderId = Long.valueOf(params.get("workOrderId").toString());
        Long processId = Long.valueOf(params.get("processId").toString());
        String inspectionType = params.get("inspectionType").toString();
        Long standardId = Long.valueOf(params.get("standardId").toString());
        
        MesQualityInspection inspection = IMesQualityInspectionService.createIPQCInspection(workOrderId, processId, inspectionType, standardId);
        return AjaxResult.success(inspection);
    }

    /**
     * 创建制造成品质检记录
     */
    @PreAuthorize("@ss.hasPermi('quality:inspection:add')")
    @Log(title = "创建制造成品质检", businessType = BusinessType.INSERT)
    @PostMapping("/createFQC")
    public AjaxResult createFQCInspection(@RequestBody Map<String, Object> params) {
        Long workOrderId = Long.valueOf(params.get("workOrderId").toString());
        Long productId = Long.valueOf(params.get("productId").toString());
        Long standardId = Long.valueOf(params.get("standardId").toString());
        
        MesQualityInspection inspection = IMesQualityInspectionService.createFQCInspection(workOrderId, productId, standardId);
        return AjaxResult.success(inspection);
    }

    /**
     * 获取质检统计数据
     */
    @PreAuthorize("@ss.hasPermi('quality:inspection:list')")
    @GetMapping("/statistics")
    public AjaxResult getInspectionStatistics(@RequestParam String inspectionType,
                                            @RequestParam String startDate,
                                            @RequestParam String endDate) {
        Date start = DateUtils.parseDate(startDate);
        Date end = DateUtils.parseDate(endDate);
        
        Map<String, Object> statistics = IMesQualityInspectionService.getInspectionStatistics(inspectionType, start, end);
        return AjaxResult.success(statistics);
    }
}